package org.yaac.server.egql.evaluator.function;

import org.yaac.server.egql.evaluator.EvaluationResult;
import org.yaac.server.egql.exception.EGQLException;
import org.yaac.server.egql.processor.ProcessData.ProcessDataRecord;
import org.yaac.shared.ErrorCode;

import com.google.appengine.api.datastore.IMHandle;
import com.google.appengine.api.datastore.IMHandle.Scheme;

/**
 * @author Max Zhu (thebbsky@gmail.com)
 *
 */
public class IMHandleFunction extends Function {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	public void validate() throws EGQLException {
		FunctionUtil.ensureParamSize(ops, 2);
	}

	@Override
	public EvaluationResult evaluate(ProcessDataRecord record) {
		EvaluationResult r0 = ops.get(0).evaluate(record);
		EvaluationResult r1 = ops.get(1).evaluate(record);
		
		if (r0.getPayload() instanceof String && r1.getPayload() instanceof String) {
			try {
				Scheme scheme = Scheme.valueOf((String) r0.getPayload());
				IMHandle val = new IMHandle(scheme, (String)r1.getPayload());
				return new EvaluationResult(val, r0, r1);
			} catch (IllegalArgumentException e) {
				// input protocol does not match enum Scheme
				return r0.withWarning(ErrorCode.W142);
			}
		} else {
			return r0.withWarning(ErrorCode.W141);
		}
	}

}
